library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
## ✓ ggplot2 3.3.5     ✓ purrr   0.3.4
## ✓ tibble  3.1.5     ✓ dplyr   1.0.7
## ✓ tidyr   1.1.3     ✓ stringr 1.4.0
## ✓ readr   1.4.0     ✓ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(gifski)
library(urbnmapr)
library(gganimate)
library(sf)
## Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1
library(transformr)
## 
## Attaching package: 'transformr'
## The following object is masked from 'package:sf':
## 
##     st_normalize
library(lubridate)
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
Plotting <- read_csv(here::here('~/CIS661/CIS661CitiBike/WITHCONT (1).csv'))#read_csv(here::here('~/CIS661/CIS661CitiBike/WITHCONT.csv'))
## 
## ── Column specification ────────────────────────────────────────────────────────
## cols(
##   time = col_character(),
##   bikeid = col_double(),
##   station_name = col_character(),
##   latitude = col_double(),
##   longitude = col_double(),
##   contamination = col_double()
## )
Plotting <- Plotting %>% 
  mutate(actualTime = dmy_hms(time))
SampleData <- Plotting %>% 
  filter(day(actualTime)==1) %>% 
  mutate(CharCont = ifelse(contamination==1, "C",
                           ifelse(contamination==0, "N", "no"))) %>% 
  mutate(minute=minute(actualTime)) %>% 
  mutate(hour=hour(actualTime)) %>% 
  arrange(hour, minute) %>% 
  mutate(plotTime=100*hour+minute)
library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
library(gapminder)
p <- SampleData %>%
  filter(plotTime<200) %>% 
  plot_ly(
    x = ~latitude, 
    y = ~longitude,
    color = ~CharCont, 
    frame = ~plotTime, 
    text = ~bikeid, 
    hoverinfo = "bikeid",
    type = 'scatter',
    mode = 'markers'
  ) %>%
  layout(
    xaxis = list(
      type = "log"
    )
  )
p
## Warning in RColorBrewer::brewer.pal(N, "Set2"): minimal value for n is 3, returning requested palette with 3 different levels

## Warning in RColorBrewer::brewer.pal(N, "Set2"): minimal value for n is 3, returning requested palette with 3 different levels
## Warning in p$x$data[firstFrame] <- p$x$frames[[1]]$data: number of items to
## replace is not a multiple of replacement length
#try fifteen minute increments, plot where bike is
#just plot contaminated over days
library(plotly)
newPlotting <- Plotting %>% 
  filter(contamination==1) %>% 
  group_by(station_name, dayNum=day(dmy_hms(time))) %>% 
  arrange(station_name, dayNum) %>% 
  mutate(dailyCont=sum(contamination)) %>% 
  select(-time, -bikeid, -actualTime) %>% 
  distinct()

plotTable <- newPlotting %>% 
  group_by(station_name) %>% 
  mutate(cont=cumsum(dailyCont)) %>% 
  ungroup()

plotTable <- plotTable %>% 
  filter(station_name!="NULL") 

plotTableLastDay <- plotTable%>% 
  filter(dayNum==30)
library(leaflet)

# define bounding box with longitude/latitude coordinates
bbox <- list(
  p1 = list(long = -74.02, lat = 40.6),
  p2 = list(long = -73.94, lat = 40.78)
)

nycimage <- leaflet() %>%
  addTiles() %>% 
  addRectangles(
    lng1 = bbox$p1$long, lat1 = bbox$p1$lat,
    lng2 = bbox$p2$long, lat2 = bbox$p2$lat,
    fillColor = "transparent"
  ) %>%
  fitBounds(
    lng1 = bbox$p1$long, lat1 = bbox$p1$lat,
    lng2 = bbox$p2$long, lat2 = bbox$p2$lat,
  )

define_image_size <- function(bbox, major_dim = 400) {
  # calculate aspect ration (width/height) from lat/long bounding box
  aspect_ratio <- abs((bbox$p1$long - bbox$p2$long) / (bbox$p1$lat - bbox$p2$lat))
  # define dimensions
  img_width <- ifelse(aspect_ratio > 1, major_dim, major_dim*aspect_ratio) %>% round()
  img_height <- ifelse(aspect_ratio < 1, major_dim, major_dim/aspect_ratio) %>% round()
  size_str <- paste(img_width, img_height, sep = ",")
  list(height = img_height, width = img_width, size = size_str)
}


image_size <- define_image_size(bbox, major_dim = 600)
image_size
## $height
## [1] 600
## 
## $width
## [1] 267
## 
## $size
## [1] "267,600"
library(devtools)
## Loading required package: usethis
library(htmlwidgets)
library(mapview)
webshot::install_phantomjs()
## It seems that the version of `phantomjs` installed is greater than or equal to the requested version.To install the requested version or downgrade to another version, use `force = TRUE`.
mapshot(nycimage, file = "~/CIS661/CIS661CitiBike/nycimage.png")
library(png)

img <- readPNG("~/CIS661/CIS661CitiBike/nycimage.png") 

h<-dim(img)[1] # image height
w<-dim(img)[2] # image width

library(rayshader)
## Warning in rgl.init(initValue, onlyNULL): RGL: unable to open X11 display
## Warning: 'rgl.init' failed, running with 'rgl.useNULL = TRUE'.
mtplot = ggplot(plotTableLastDay) +
  geom_point(aes(x = latitude, y = longitude, color = cont)) +
  scale_color_continuous(limits = c(0, 120))+
  scale_x_continuous(breaks=c(40.65, 40.7, 40.75))
mtplot

par(mfrow = c(1, 2))
plot_gg(mtplot, width = 3.5, raytrace = FALSE, preview = TRUE)

plot_gg(mtplot, width = 3.5, multicore = TRUE, windowsize = c(800, 800),
        zoom = 0.85, phi = 35, theta = 30, sunangle = 225, soliddepth = -100)

render_snapshot(clear = TRUE)

#cleaning W 20 St & 11 Ave
Plotting %>% 
  arrange(bikeid, time) %>% 
  group_by(bikeid) %>% 
  mutate(temp=1) %>% 
  mutate(numEntries=ave(temp, FUN=cumsum))
## # A tibble: 577,703 × 9
## # Groups:   bikeid [5,794]
##    time             bikeid station_name           latitude longitude contamination
##    <chr>             <dbl> <chr>                     <dbl>     <dbl>         <dbl>
##  1 05JUN13:00:09:05  14529 Forsyth St & Canal St      40.7     -74.0             0
##  2 05JUN13:02:38:44  14529 Market St & Cherry St      40.7     -74.0             0
##  3 05JUN13:03:14:08  14529 W 45 St & 8 Ave            40.8     -74.0             0
##  4 05JUN13:17:43:47  14529 W 38 St & 8 Ave            40.8     -74.0             0
##  5 05JUN13:18:13:00  14529 W 38 St & 8 Ave            40.8     -74.0             0
##  6 05JUN13:18:32:40  14529 E 15 St & Irving Pl        40.7     -74.0             0
##  7 06JUN13:00:21:12  14529 Greenwich Ave & 8 Ave      40.7     -74.0             0
##  8 06JUN13:19:29:44  14529 Leonard St & Church St     40.7     -74.0             0
##  9 08JUN13:12:02:58  14529 Leonard St & Church St     40.7     -74.0             0
## 10 09JUN13:11:52:08  14529 Carmine St & 6 Ave         40.7     -74.0             0
## # … with 577,693 more rows, and 3 more variables: actualTime <dttm>,
## #   temp <dbl>, numEntries <dbl>
cleanOnePlotting <- Plotting %>%
  arrange(bikeid, time) %>% 
  group_by(bikeid) %>% 
  mutate(numEntries=ave(bikeid/bikeid, FUN=cumsum)) %>% 
  mutate(contFlag=contamination) %>% 
  mutate(contFlag=ifelse(station_name=="W 20 St & 11 Ave", 10, contFlag)) %>% 
  mutate(isCleaned=cumsum(contFlag))
  
cleanOnePlotting <- cleanOnePlotting %>% 
  mutate(contamination=ifelse(isCleaned>numEntries, 0, contamination))
library(plotly)
newCleanOnePlotting <- cleanOnePlotting %>% 
  filter(contamination==1) %>% 
  group_by(station_name, dayNum=day(dmy_hms(time))) %>% 
  arrange(station_name, dayNum) %>% 
  mutate(dailyCont=sum(contamination)) %>% 
  select(-time, -bikeid, -actualTime, -numEntries, -contamination, -isCleaned) %>% 
  distinct()

cleanOnePlotTable <- newCleanOnePlotting %>% 
  group_by(station_name) %>% 
  mutate(cont=cumsum(dailyCont)) %>% 
  ungroup()

cleanOnePlotTable <- cleanOnePlotTable %>% 
  filter(station_name!="NULL") 

cleanOnePlotTableLastDay <- cleanOnePlotTable%>% 
  filter(dayNum==30)
mtplotcleanone = ggplot(cleanOnePlotTableLastDay) +
  geom_point(aes(x = latitude, y = longitude, color = cont)) +
  scale_color_continuous(limits = c(0, 120))+
  scale_x_continuous(breaks=c(40.65, 40.7, 40.75))
mtplotcleanone

par(mfrow = c(1, 2))
plot_gg(mtplotcleanone, width = 3.5, raytrace = FALSE, preview = TRUE)

plot_gg(mtplotcleanone, width = 3.5, multicore = TRUE, windowsize = c(800, 800),
        zoom = 0.85, phi = 35, theta = 30, sunangle = 225, soliddepth = -100)

render_snapshot(clear = TRUE)